//The contents of this file are subject to the Mozilla Public License Version 1.1
//(the "License"); you may not use this file except in compliance with the
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
//Software distributed under the License is distributed on an "AS IS" basis,
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
//for the specific language governing rights and
//limitations under the License.
//
//The Original Code is "The Columba Project"
//
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003.
//
//All Rights Reserved.
package org.columba.mail.gui.composer;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.UIManager;

import org.columba.core.resourceloader.ImageLoader;
import org.columba.ristretto.message.MimeHeader;
import org.columba.ristretto.message.MimePart;
import org.columba.ristretto.message.MimeType;
import org.frapuccino.iconpanel.IconPanel;

/**
 * Attachment view. Used in the composer to show a list of attachments. Is part
 * of a controller-view framework together with AttachmentController.
 * 
 * @author frdietz
 * @author redsolo
 */

public class AttachmentView extends IconPanel {

	/** Reference to the controller controlling this view */
	private AttachmentController attachmentController;
	
	private AttachmentImageIconLoader attachmentIconLoader;

	/** Underlying data model for the list view */
	private DefaultListModel listModel;

	/**
	 * Default constructor. Sets up the view and stores a reference to the
	 * controller for later use.
	 * 
	 * @param controller
	 *            Reference to the controller of this view
	 */
	public AttachmentView(AttachmentController controller) {
		super();

		attachmentController = controller;

		listModel = new DefaultListModel();

		setOpaque(true);

		setBackground(UIManager.getColor("List.background"));

		attachmentIconLoader = new AttachmentImageIconLoader();
		
		setDoubleClickAction(new OpenAttachmentAction(this));
		
		//TODO Let the AttachmentViewer get the focus so that this works
		addKeyListener( new KeyListener() {

			public void keyPressed(KeyEvent e) {
				if( e.getKeyCode() == KeyEvent.VK_DELETE) {
					removeSelected();
				}
				
			}

			public void keyReleased(KeyEvent e) {
				
			}

			public void keyTyped(KeyEvent e) {
			}});
		
		//setModel(listModel);

		//setCellRenderer(new ListRenderer());
	}

	/**
	 * Installs the attachment controller as listener
	 * 
	 * @param c
	 *            Controller of this view
	 */
	public void installListener(AttachmentController c) {
		addKeyListener(c);
	}

	/**
	 * Adds a popup listener
	 * 
	 * @param a
	 *            Listener to add
	 */
	public void addPopupListener(MouseAdapter a) {
		addMouseListener(a);
	}

	/**
	 * Adds an attachment to be displayed in the view
	 * 
	 * @param mp
	 *            Attachment to add
	 */
	public void add(MimePart mp) {
		listModel.addElement(mp);

		MimeHeader header = mp.getHeader();

		MimeType mimeType = header.getMimeType();

		ImageIcon icon = attachmentIconLoader.getImageIcon(mimeType
				.getType(), mimeType.getSubtype());

		String text = header.getFileName();
		if( text==null || text.length() == 0 ) {
			if( header.getContentDescription() != null) {
				text = header.getContentDescription();
			} else {
				text = mimeType.toString();
			}			
		}
		
		
		//      Get Tooltip for Icon
		StringBuffer tooltip = new StringBuffer();
		tooltip.append("<html><body>");

		if (mp.getHeader().getFileName() != null) {
			tooltip.append(header.getFileName());
			tooltip.append(" - ");
		}

		tooltip.append("<i>");

		if (header.getContentDescription() != null) {
			tooltip.append(header.getContentDescription());
		} else {
			tooltip.append(mimeType.getType());
			tooltip.append("/");
			tooltip.append(mimeType.getSubtype());
		}

		tooltip.append("</i></body></html>");
		add(icon, text, tooltip.toString());
	}

	public void removeSelected() {
		// remove from model
		int[] indices = getSelectedIndices();

		for (int i = 0; i < indices.length; i++) {
			listModel.removeElementAt(indices[i]);

		}

		// remove from view
		super.removeSelected();
	}

	/**
	 * Clears the view, i.e. removes all attachments.
	 */
	public void clear() {
		// clear model
		listModel.clear();
		
		// clear view
		removeAll();
	}

	/**
	 * Gets an attachment from the view by index
	 * 
	 * @param index
	 *            Index of attachment (zero based)
	 * @return The specified attachment
	 */
	public MimePart get(int index) {
		return (MimePart) listModel.get(index);
	}

	/**
	 * Gets number of attachments currently displayed in the view.
	 * 
	 * @return the number of attachments currently displayed in the view.
	 */
	public int count() {
		return listModel.size();
	}

	/**
	 * Selects the list item that is at the position in the component/list.
	 * 
	 * @param x
	 *            the x pos.
	 * @param y
	 *            the y pos.
	 */
	public void fixSelection(int x, int y) {
		/*
		 * int index = locationToIndex(new Point(x, y));
		 * 
		 * setSelectedIndex(index);
		 */
	}

	/**
	 * @return Returns the controller for the view.
	 */
	public AttachmentController getController() {
		return attachmentController;
	}
	
	/**
	 * Imageloader using a content-type and subtype to determine the image name.
	 * <p>
	 * Automatically falls back to the default icon.
	 * 
	 * @author fdietz
	 */
	class AttachmentImageIconLoader {

		/**
		 * Utility constructor.
		 */
		private AttachmentImageIconLoader() {
		}

		/**
		 * Returns the image icon for the content type.
		 * 
		 * @param contentType
		 *            content type
		 * @param contentSubtype
		 *            content sub type
		 * @return an Image Icon for the content type.
		 */
		public ImageIcon getImageIcon(String contentType, String contentSubtype) {
			StringBuffer buf = new StringBuffer();
			buf.append("gnome-");
			buf.append(contentType);
			buf.append("-");
			buf.append(contentSubtype);
			buf.append(".png");

			ImageIcon icon = ImageLoader.getMimetypeIcon(buf.toString());

			if (icon == null) {
				icon = ImageLoader.getMimetypeIcon("gnome-"
						+ contentType + ".png");
			}

			if (icon == null) {
				icon = ImageLoader.getMimetypeIcon("gnome-text.png");
			}

			return icon;
		}
	}
}